package com.maltys.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;

/**
 * @author malty
 */
@RestController
@RequestMapping("/test")
public class RedissonTestController {

    private static int stock = 100;
    @Autowired
    private RedissonClient redissonClient;

    @RequestMapping("/v4/redis/lock")
    public void testLock() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                RLock lock = redissonClient.getLock("wuchen-lock");
                try {
                    lock.lock();
                    stock--;
                    System.out.println(Thread.currentThread().getName() + "加锁成功:" + stock);
                } finally {
                    lock.unlock();
                    countDownLatch.countDown();
                }

            }, "mythread" + i).start();
        }
        countDownLatch.await();
        System.out.println(stock);
    }

    @RequestMapping("/v4/redis/try_lock")
    public void testTryLock() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            int a = i;
            new Thread(() -> {
                RLock lock = redissonClient.getLock("redissonLock");
                String tName = "t" + a;
                //加锁操作
                try {
                    while (true) {
                        //if (lock.tryLock(100, TimeUnit.SECONDS)) {
                        if (lock.tryLock()) {
                            System.out.println(tName + "加锁成功");
                            System.out.println(tName + " working...");
                            break;
                        } else {
                            //加锁不成功
                            System.out.println(tName + "加锁失败");
                            Thread.sleep(10);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                    countDownLatch.countDown();
                    System.out.println(tName + "解锁成功");
                }
            }, "t" + a).start();
        }
        countDownLatch.await();
    }
}
